package com.totoro.tygeneratedragonblock.manager;

import com.totoro.tygeneratedragonblock.TyGenerateDragonBlock;
import com.totoro.tygeneratedragonblock.constants.StaticSystemVarConst;
import com.totoro.tygeneratedragonblock.pojo.BlockDefinition;
import com.totoro.tygeneratedragonblock.utils.ColorUtil;
import com.totoro.tygeneratedragonblock.utils.FileUtil;
import lombok.Getter;
import org.bukkit.Bukkit;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.YamlConfiguration;

import java.io.File;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Totoro
 * @version 0.1.0
 * @date 2025/8/10 - 2:43
 * @description 方块定义管理器
 **/
public class BlocksManager {
    private final TyGenerateDragonBlock plugin;

    private final static File BLOCKS_FOLDER = new File(TyGenerateDragonBlock.getInstance().getDataFolder().getPath() + StaticSystemVarConst.FILE_SEPARATOR + StaticSystemVarConst.BLOCKS_FOLDER_DEFAULT_NAME);

    /* 所有方块定义存储 */
    @Getter private final Map<String, BlockDefinition> blockDefinitions = new LinkedHashMap<>();

    public BlocksManager(TyGenerateDragonBlock plugin) {
        this.plugin = plugin;
        reloadBlocksFile();
    }

    /**
     * 生成默认文件夹和示例配置
     */
    public void initBlocksFile() {
        // 如果排行文件不存在则创建
        if(! BLOCKS_FOLDER.exists()) {
            BLOCKS_FOLDER.mkdirs();
        }
        // 存储默认的配置
        plugin.saveResource("blocks/默认方块.yml", true);
    }

    /**
     * @author totoro
     * @description 刷新方块定义配置文件
     * @date  3:03
     * @param []
     * @return void
     **/
    public void reloadBlocksFile() {
        initBlocksFile();
        blockDefinitions.clear();
        List<File> allBlockFiles = FileUtil.getAllFiles(BLOCKS_FOLDER);
        for (File allBlockFile : allBlockFiles) {
            if(allBlockFile.isFile()) {
                if(allBlockFile.getName().endsWith(".yml")) {
                    YamlConfiguration blockFileConfig = YamlConfiguration.loadConfiguration(allBlockFile);
                    Set<String> blockKeys = blockFileConfig.getKeys(false);
                    for (String blockId : blockKeys) {
                        if(blockFileConfig.isConfigurationSection(blockId)) {
                            ConfigurationSection blockConfig = blockFileConfig.getConfigurationSection(blockId);
                            String blockName = ColorUtil.color(blockConfig.getString("block-name"));
                            String match = blockConfig.getString("match");
                            List<String> itemMatch = blockConfig.getStringList("item-match");
                            if(null != itemMatch && !itemMatch.isEmpty()) {
                                itemMatch = itemMatch.stream().map(ColorUtil::color).collect(Collectors.toList());
                            }
                            List<String> condition = blockConfig.getStringList("condition");
                            if(null != condition && !condition.isEmpty()) {
                                condition = condition.stream().map(ColorUtil::color).collect(Collectors.toList());
                            }
                            Map<String, String> valueSet = new HashMap<>();
                            ConfigurationSection valueSetSection = blockConfig.getConfigurationSection("value-set");
                            if(null != valueSetSection) {
                                Set<String> valueSetKeys = valueSetSection.getKeys(false);
                                for (String valueSetKey : valueSetKeys) {
                                    String newValueSetKey = "{" + valueSetKey + "}";
                                    valueSet.put(newValueSetKey, valueSetSection.getString(valueSetKey));
                                }
                            }

                            List<String> drops = blockConfig.getStringList("drops");
                            if(null != drops && !drops.isEmpty()) {
                                drops = drops.stream().map(ColorUtil::color).collect(Collectors.toList());
                            }
                            String exp = blockConfig.getString("exp");
                            List<String> actions = blockConfig.getStringList("actions");
                            if(null != actions && !actions.isEmpty()) {
                                actions = actions.stream().map(ColorUtil::color).collect(Collectors.toList());
                            }
                            BlockDefinition blockDefinition = new BlockDefinition(blockId, blockName, match, null, itemMatch, condition, valueSet, drops, exp, actions);
                            // 初始化悬浮字xyz，先使用默认值
                            BlockDefinition.NameDisplayLocation nameDisplayLocation = blockDefinition.new NameDisplayLocation(0.5, 1.5, 0.5);
                            // 读取配置，如果没有直接不对默认值做任何修改
                            if (blockConfig.isConfigurationSection("name-display-location")) {
                                ConfigurationSection nameDisplayLocationSection = blockConfig.getConfigurationSection("name-display-location");
                                nameDisplayLocation.setX(nameDisplayLocationSection.getDouble("x", 0.5));
                                nameDisplayLocation.setY(nameDisplayLocationSection.getDouble("y", 1.5));
                                nameDisplayLocation.setZ(nameDisplayLocationSection.getDouble("z", 0.5));
                            }
                            blockDefinition.setNameDisplayLocation(nameDisplayLocation);
                            blockDefinitions.put(blockId, blockDefinition);
                            plugin.getServer().getConsoleSender().sendMessage(StaticSystemVarConst.CONSOLE_PREFIX + ColorUtil.color(String.format("&f成功加载方块定义信息: [&c%s&f]", blockId)));
                        }
                    }
                }
            }
        }
    }
}
